import { baseURL } from '@/api/_client.ts';
import { getInvasiveSpeciesList } from '@/api/agriculture.ts';
import { defineStore } from 'pinia';
import { computed, ref } from 'vue';

export const useKnowledgeStore = defineStore(
  'KnowledgeStore',
  () => {
    // 定义响应式数据
    const tabImages = ref<any>([]);
    const loading = ref<boolean>(true);

    // 获取入侵物种数据
    const getHomeInvasiveSpecie = async () => {
      const req = {
        pageNo: 1,
        pageSize: 4,
      };
      try {
        const res = await getInvasiveSpeciesList(req);
        const { data } = res;
        tabImages.value = data.map((item) => {
          const imageUrl = item.attributes.image?.data?.attributes?.url;
          return {
            id: item.id,
            ChineseName: item.attributes.ChineseName,
            src: imageUrl ? baseURL + `${imageUrl}` : 'default-image-url',
            scientificName: item.attributes.ScientificName,
          };
        });
      } catch (error) {
        console.error('Error fetching data:', error);
      } finally {
        loading.value = false;
      }
    };

    // 计算属性，返回tabImages
    const getTabImages = computed(() => tabImages.value);

    const getTabImagesLoading = computed(() => {
      return loading.value;
    });

    return {
      loading,
      tabImages,
      getHomeInvasiveSpecie,
      getTabImages,
      getTabImagesLoading,
    };
  },
  {
    persist: true,
  }
);
